const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');

// 模拟用户数据
const users = [
    {
        id: 1,
        username: 'zhangsan',
        password: '123456',
        name: '张三',
        role: 'pm',
        department: '开发部'
    },
    {
        id: 2,
        username: 'lisi',
        password: '123456',
        name: '李四',
        role: 'frontend',
        department: '前端部'
    },
    {
        id: 3,
        username: 'wangwu',
        password: '123456',
        name: '王五',
        role: 'backend',
        department: '后端部'
    },
    {
        id: 4,
        username: 'zhaoliu',
        password: '123456',
        name: '赵六',
        role: 'member',
        department: '测试部'
    },
    {
        id: 5,
        username: 'liming',
        password: '123456',
        name: '李明',
        role: 'minister',
        department: '开发部'
    }
];

// 模拟项目数据
const projects = [
    {
        id: 1001,
        name: '项目A',
        description: '这是一个重要的项目A',
        status: 'active',
        progress: 75,
        start_date: '2023-01-01',
        end_date: '2023-06-30',
        pm_id: 1,
        pm_name: '张三',
        frontend_id: 2,
        frontend_name: '李四',
        backend_id: 3,
        backend_name: '王五',
        git_url: 'https://github.com/example/project-a',
        created_at: '2023-01-01 10:00:00',
        updated_at: '2023-05-15 15:30:00',
        modules: [
            {
                id: 201,
                name: '用户管理模块',
                description: '用户注册、登录、权限管理等功能',
                type: 'frontend',
                status: 'completed',
                progress: 100,
                start_date: '2023-01-10',
                end_date: '2023-02-20',
                completed_at: '2023-02-15 10:30:00'
            },
            {
                id: 202,
                name: '数据管理模块',
                description: '数据的增删改查功能',
                type: 'backend',
                status: 'active',
                progress: 60,
                start_date: '2023-02-01',
                end_date: '2023-04-30',
                completed_at: null
            }
        ],
        documents: [
            {
                id: 301,
                name: 'API文档.docx',
                type: 'api',
                creator_id: 1,
                creator_name: '张三',
                created_at: '2023-01-05 15:45:00',
                updated_at: '2023-03-10 11:20:00',
                url: 'https://cdn.example.com/docs/201/API文档.docx'
            },
            {
                id: 302,
                name: '需求文档.pdf',
                type: 'requirement',
                creator_id: 5,
                creator_name: '李明',
                created_at: '2023-01-02 09:30:00',
                updated_at: '2023-01-15 14:20:00',
                url: 'https://cdn.example.com/docs/202/需求文档.pdf'
            }
        ]
    },
    {
        id: 1002,
        name: '项目B',
        description: '项目B的描述信息',
        status: 'completed',
        progress: 100,
        start_date: '2023-02-01',
        end_date: '2023-05-31',
        pm_id: 1,
        pm_name: '张三',
        frontend_id: 2,
        frontend_name: '李四',
        backend_id: 3,
        backend_name: '王五',
        git_url: 'https://github.com/example/project-b',
        created_at: '2023-02-01 08:00:00',
        updated_at: '2023-05-31 18:00:00',
        modules: [
            {
                id: 203,
                name: '报表模块',
                description: '数据统计和报表展示',
                type: 'frontend',
                status: 'completed',
                progress: 100,
                start_date: '2023-02-10',
                end_date: '2023-04-15',
                completed_at: '2023-04-10 16:45:00'
            }
        ],
        documents: [
            {
                id: 303,
                name: '测试报告.docx',
                type: 'test',
                creator_id: 4,
                creator_name: '赵六',
                created_at: '2023-05-20 10:15:00',
                updated_at: '2023-05-25 14:30:00',
                url: 'https://cdn.example.com/docs/203/测试报告.docx'
            }
        ]
    },
    {
        id: 1003,
        name: '项目C',
        description: '项目C的详细描述',
        status: 'paused',
        progress: 30,
        start_date: '2023-03-01',
        end_date: '2023-08-31',
        pm_id: 2,
        pm_name: '李四',
        frontend_id: 2,
        frontend_name: '李四',
        backend_id: 3,
        backend_name: '王五',
        git_url: 'https://github.com/example/project-c',
        created_at: '2023-03-01 14:30:00',
        updated_at: '2023-04-20 11:45:00',
        modules: [
            {
                id: 204,
                name: '支付模块',
                description: '在线支付功能集成',
                type: 'backend',
                status: 'paused',
                progress: 30,
                start_date: '2023-03-15',
                end_date: '2023-06-30',
                completed_at: null
            }
        ],
        documents: [
            {
                id: 304,
                name: '设计文档.pdf',
                type: 'design',
                creator_id: 2,
                creator_name: '李四',
                created_at: '2023-03-05 16:20:00',
                updated_at: '2023-03-20 09:45:00',
                url: 'https://cdn.example.com/docs/204/设计文档.pdf'
            }
        ]
    }
];

// 简单的JWT生成函数
function generateToken(user) {
    const header = { alg: 'HS256', typ: 'JWT' };
    const payload = {
        user_id: user.id,
        username: user.username,
        role: user.role,
        exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60) // 24小时过期
    };
    
    const headerBase64 = Buffer.from(JSON.stringify(header)).toString('base64');
    const payloadBase64 = Buffer.from(JSON.stringify(payload)).toString('base64');
    const signature = Buffer.from('your-secret-key').toString('base64');
    
    return `${headerBase64}.${payloadBase64}.${signature}`;
}

// 简单的JWT验证函数
function verifyToken(token) {
    try {
        const parts = token.split('.');
        if (parts.length !== 3) return null;
        
        const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());
        
        // 检查是否过期
        if (payload.exp < Math.floor(Date.now() / 1000)) {
            return null;
        }
        
        return payload;
    } catch (error) {
        return null;
    }
}

// 发送JSON响应的辅助函数
function sendJsonResponse(res, statusCode, data) {
    res.writeHead(statusCode, {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization'
    });
    res.end(JSON.stringify(data));
}

// 获取请求体的辅助函数
function getRequestBody(req) {
    return new Promise((resolve) => {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
        req.on('end', () => {
            try {
                resolve(JSON.parse(body));
            } catch (error) {
                resolve({});
            }
        });
    });
}

// 创建HTTP服务器
const server = http.createServer(async (req, res) => {
    const parsedUrl = url.parse(req.url, true);
    const pathname = parsedUrl.pathname;
    const method = req.method;

    // 处理CORS预检请求
    if (method === 'OPTIONS') {
        res.writeHead(200, {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization'
        });
        res.end();
        return;
    }

    // 登录API
    if (pathname === '/auth/login' && method === 'POST') {
        try {
            const body = await getRequestBody(req);
            const { username, password } = body;

            // 验证用户名和密码
            const user = users.find(u => u.username === username && u.password === password);
            
            if (user) {
                const token = generateToken(user);
                const userInfo = {
                    username: user.name,
                    role: user.role,
                    department: user.department
                };
                
                sendJsonResponse(res, 200, {
                    code: 200,
                    message: '登录成功',
                    data: {
                        user_info: userInfo,
                        token: token
                    }
                });
            } else {
                sendJsonResponse(res, 401, {
                    code: 401,
                    message: '用户名或密码错误',
                    data: null
                });
            }
        } catch (error) {
            sendJsonResponse(res, 500, {
                code: 500,
                message: '服务器内部错误',
                data: null
            });
        }
        return;
    }

    // 获取用户信息API
    if (pathname === '/auth/user-info' && method === 'GET') {
        const authHeader = req.headers.authorization;
        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            sendJsonResponse(res, 401, {
                code: 401,
                message: '未提供有效的认证令牌',
                data: null
            });
            return;
        }

        const token = authHeader.substring(7);
        const payload = verifyToken(token);
        
        if (!payload) {
            sendJsonResponse(res, 401, {
                code: 401,
                message: '认证令牌无效或已过期',
                data: null
            });
            return;
        }

        const user = users.find(u => u.id === payload.user_id);
        if (user) {
            sendJsonResponse(res, 200, {
                code: 200,
                message: '获取用户信息成功',
                data: {
                    username: user.name,
                    role: user.role,
                    department: user.department
                }
            });
        } else {
            sendJsonResponse(res, 404, {
                code: 404,
                message: '用户不存在',
                data: null
            });
        }
        return;
    }

    // 获取项目列表API
    if (pathname === '/projects' && method === 'GET') {
        const authHeader = req.headers.authorization;
        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            sendJsonResponse(res, 401, {
                code: 401,
                message: '未提供有效的认证令牌',
                data: null
            });
            return;
        }

        const token = authHeader.substring(7);
        const payload = verifyToken(token);
        
        if (!payload) {
            sendJsonResponse(res, 401, {
                code: 401,
                message: '认证令牌无效或已过期',
                data: null
            });
            return;
        }

        const user = users.find(u => u.id === payload.user_id);
        if (!user) {
            sendJsonResponse(res, 404, {
                code: 404,
                message: '用户不存在',
                data: null
            });
            return;
        }

        let filteredProjects;
        if (user.role === 'minister') {
            // 部长可以查看所有项目
            filteredProjects = projects;
        } else {
            // 其他角色只能查看自己负责的项目
            filteredProjects = projects.filter(project => project.pm_id === user.id);
        }

        sendJsonResponse(res, 200, {
            code: 200,
            message: '获取项目列表成功',
            data: filteredProjects
        });
        return;
    }

    // 获取项目详情API
    if (pathname.startsWith('/projects/') && method === 'GET') {
        const authHeader = req.headers.authorization;
        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            sendJsonResponse(res, 401, {
                code: 401,
                message: '未提供有效的认证令牌',
                data: null
            });
            return;
        }

        const token = authHeader.substring(7);
        const payload = verifyToken(token);
        
        if (!payload) {
            sendJsonResponse(res, 401, {
                code: 401,
                message: '认证令牌无效或已过期',
                data: null
            });
            return;
        }

        const user = users.find(u => u.id === payload.user_id);
        if (!user) {
            sendJsonResponse(res, 404, {
                code: 404,
                message: '用户不存在',
                data: null
            });
            return;
        }

        const projectId = parseInt(pathname.split('/')[2]);
        const project = projects.find(p => p.id === projectId);
        
        if (!project) {
            sendJsonResponse(res, 404, {
                code: 404,
                message: '项目不存在',
                data: null
            });
            return;
        }

        // 检查权限：部长可以查看所有项目，其他角色只能查看自己负责的项目
        if (user.role !== 'minister' && project.pm_id !== user.id) {
            sendJsonResponse(res, 403, {
                code: 403,
                message: '没有权限查看该项目详情',
                data: null
            });
            return;
        }

        sendJsonResponse(res, 200, {
            code: 200,
            message: '获取项目详情成功',
            data: project
        });
        return;
    }

    // 测试API
    if (pathname === '/api/test' && method === 'GET') {
        sendJsonResponse(res, 200, {
            code: 200,
            message: '服务器运行正常',
            data: {
                timestamp: new Date().toISOString(),
                server: 'Simple Node.js Server'
            }
        });
        return;
    }

    // 静态文件服务
    const filePath = path.join(__dirname, pathname === '/' ? 'login.html' : pathname);
    
    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
            res.end('<h1>404 - 文件未找到</h1>');
            return;
        }

        const ext = path.extname(filePath);
        let contentType = 'text/html';
        
        switch (ext) {
            case '.js':
                contentType = 'text/javascript';
                break;
            case '.css':
                contentType = 'text/css';
                break;
            case '.json':
                contentType = 'application/json';
                break;
            case '.png':
                contentType = 'image/png';
                break;
            case '.jpg':
                contentType = 'image/jpg';
                break;
        }

        res.writeHead(200, { 'Content-Type': contentType });
        res.end(data);
    });
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log('测试用户信息:');
    users.forEach(user => {
        console.log(`用户名: ${user.username}, 密码: ${user.password}, 角色: ${user.role}`);
    });
}); 